import type { RequestMap } from 'my-ts-core/security';

export interface RequestMapQuery {
  queryAll(): Promise<RequestMap[]>;
}

export async function getCachedRequestMaps(query: RequestMapQuery): Promise<RequestMap[]> {
  if (cachedRequestMaps?.length == 0) {
    // If another reload is already in progress, wait for it
    if (!reloadLock) {
      reloadLock = reloadCachedRequestMaps(query);
      await reloadLock;
      reloadLock = null;
    } else {
      await reloadLock;
    }
  }

  return cachedRequestMaps!;
}

/**
 * Reloads the cache
 */
async function reloadCachedRequestMaps(query: RequestMapQuery): Promise<void> {
  cachedRequestMaps = await query.queryAll();
}

// Shared cache
let cachedRequestMaps: RequestMap[] | null = null;

// Lock promise to avoid race conditions
let reloadLock: Promise<void> | null = null;
